package com.cmcc.passenger.ui.callpaging

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.passenger.R
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.OrderDetail
import com.cmcc.passenger.databinding.ActivityCallOrderDetailBinding
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.fragment.AppCallAlertDialog
import com.cmcc.passenger.ui.fragment.AppProgressDialog
import com.cmcc.passenger.ui.fragment.CancelReasonDialogFragment
import com.cmcc.passenger.ui.utils.NumberUtils
import com.cmcc.shared.utils.TextViewUtil
import com.cmcc.shared.utils.showToast
import kotlinx.android.synthetic.main.activity_call_order_detail.view.*
import kotlinx.android.synthetic.main.layout_call_order_cancle_info.view.*
import kotlinx.android.synthetic.main.layout_call_order_done_info.view.*
import kotlinx.android.synthetic.main.layout_call_order_driver_info.view.*
import kotlinx.android.synthetic.main.layout_call_order_driver_info.view.phone_call
import kotlinx.android.synthetic.main.layout_call_order_driver_info.view.tv_01
import kotlinx.android.synthetic.main.layout_call_order_driver_info.view.tv_11
import kotlinx.android.synthetic.main.layout_call_order_driver_info.view.tv_21

@Route(path = PassPath.CALL_ORDER_DETAIL)
class CallOrderDetailActivity : BasicActivity() {

    private lateinit var binding: ActivityCallOrderDetailBinding
    private var progressDialog: AppProgressDialog? = null
    private lateinit var viewModel: CallOrderViewModel
    private var orderRequest: OrderDetail? = null
    private var flag = 0


    override fun initialize(savedInstanceState: Bundle?) {
        viewModel = ViewModelProviders.of(this).get(CallOrderViewModel::class.java)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_call_order_detail)
        binding.toolbar.toolbar.setNavigationOnClickListener { finish() }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        progressDialog = AppProgressDialog(this)
        binding.toolbar.title.text = getString(R.string.order_doing_title)
        binding.dynamic.displayedChild = 0
    }

    override fun onResume() {
        super.onResume()
        flag = intent.getIntExtra("flag", 0)
        val id = intent.getStringExtra("order_id")
        if (!id.isNullOrBlank()) {
            viewModel.getOrderDetail(id)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val id = intent?.getStringExtra("order_id")
        if (!id.isNullOrBlank()) {
            viewModel.getOrderDetail(id)
        }
    }

    fun takeCall(view: View) {
        AppCallAlertDialog(this).setContent("62325253")
            .setNavigation(getString(R.string.cancel), null)
            .setPositive(getString(R.string.call_phone),
                View.OnClickListener {
                    val data = Uri.parse("tel:62325253")
                    val intent = Intent(Intent.ACTION_DIAL, data)
                    startActivity(intent)
                }).show()
    }


    override fun initObserver(savedInstanceState: Bundle?) {
        super.initObserver(savedInstanceState)
        viewModel.orderDetail.observe(this, Observer { orderDetail ->
            orderRequest = orderDetail
            when (orderDetail?.status) {
                6 -> {
                    showFinishView(orderDetail)
                }

                7 -> {
                    showCancleView(orderDetail)
                }
                else -> {
                    showDoingView(orderDetail)
                }

            }
            TextViewUtil.setTextViewByLimit(
                binding.onOrderDirection.orderType,
                orderRequest?.type == 1,
                getString(R.string.order_real_time),
                getString(R.string.order_reservation)
            )
            binding.onOrderDirection.direction.directionStart.text =
                orderRequest?.startAddress
            binding.onOrderDirection.direction.directionEnd.text =
                orderRequest?.endAddress
            binding.onOrderRemarks.orderRemarks1.text =
                getCatTypeName(orderRequest?.carCategory?.name)
            binding.onOrderRemarks.orderRemarks2.text =
                        getTunnelName(orderRequest?.tunnel?.name)
            binding.onOrderRemarks.orderRemarks3.text =
                        getStationName(orderRequest?.stationIndex)
            binding.onOrderRemarks.remarkCount.text = getRemark(orderRequest?.remark)
            val bountyFee = orderRequest?.bountyFee
            if (!bountyFee.isNullOrEmpty()) {
                var feeDouble = orderRequest?.bountyFee?.toDouble()
                binding.onOrderTip.amount_of_tip.text = NumberUtils.forNormalMatNumber(feeDouble!!)
            } else {
                binding.onOrderTip.amount_of_tip.text = "0"
            }

        })

        viewModel.cancelCall.observe(this, Observer { res ->
            progressDialog?.dismiss()
            res?.let {
                if (res.code == 200) {
                    orderRequest?.let { showCancleView(it) }
                } else {
                    showToast(this, res.msg)
                }
            }
        })

        viewModel.confirmCall.observe(this, Observer { res ->
            progressDialog?.dismiss()
            res?.let {
                if (res.code == 200) {
                    orderRequest?.let { showFinishView(it) }
                } else {
                    showToast(this, res.msg)
                }
            }
        })

        viewModel.isShowOver.observe(this, Observer {
            orderRequest?.let { showFinishView(it) }
        })

    }

    private fun showDoingView(orderDetail: OrderDetail) {
        binding.toolbar.title.text = getString(R.string.order_doing_title)
        binding.dynamic.displayedChild = 0
//                    viewModel.doneCountDownTimer(orderDetail.createTime)
        binding.bottomLl.visibility = View.VISIBLE
        binding.buttonCountDown.visibility = View.GONE
        binding.callOrderDoingInfo.tv_01.text = orderDetail.driver.name
        binding.callOrderDoingInfo.tv_03.text = orderDetail.orderNumber
        binding.callOrderDoingInfo.tv_11.text = orderDetail.driverCarIdCard
        binding.callOrderDoingInfo.tv_21.text = orderDetail.driver.phone
        binding.callOrderDoingInfo.create_time.text = orderDetail.createTime

        binding.callOrderDoingInfo.phone_call.setOnClickListener {
            AppCallAlertDialog(this).setContent(orderDetail.driver.phone)
                .setNavigation(getString(R.string.cancel), null)
                .setPositive(getString(R.string.call_phone),
                    View.OnClickListener {
                        val data = Uri.parse("tel:${orderDetail.driver.phone}")
                        val intent = Intent(Intent.ACTION_DIAL, data)
                        startActivity(intent)
                    }).show()
        }
        binding.navigationButton.setOnClickListener {
            val fragment = CancelReasonDialogFragment.newFragment()
            fragment.setOnCommitClickListener(object :
                CancelReasonDialogFragment.OnCommitClickListener {
                override fun onCommitClick(remark: String) {
                    progressDialog?.show()
                    viewModel.cancelOrder(orderRequest?.id ?: "", remark)
                }

            })
            fragment.show(supportFragmentManager, "CancelReasonDialogFragment")
        }

        binding.buttonSave.setOnClickListener {
            AppCallAlertDialog(this).setContent(getString(R.string.call_driver_is_come))
                .setNavigation(getString(R.string.let_me_see), null)
                .setPositive(getString(R.string.yes),
                    View.OnClickListener {
                        progressDialog?.show()
                        viewModel.confirmCall(orderRequest?.id ?: "")
                    }).show()
        }
    }

    private fun showCancleView(orderDetail: OrderDetail) {
        binding.toolbar.title.text = getString(R.string.passenger_order_has_canceled)
        binding.dynamic.displayedChild = 1
        binding.bottomLl.visibility = View.GONE
        binding.buttonCountDown.visibility = View.GONE
        binding.callOrderCancleInfo.tv_cancel_02.text = orderDetail.orderNumber
        binding.callOrderCancleInfo.create_time_cancel.text = orderDetail.createTime
    }

    private fun showFinishView(orderDetail: OrderDetail) {
        binding.toolbar.title.text = getString(R.string.driver_finish)
        binding.dynamic.displayedChild = 2
        binding.bottomLl.visibility = View.GONE
        when(flag) {
            0 -> {
                binding.buttonCountDown.visibility = View.VISIBLE
                binding.buttonCountDown.text = getString(R.string.count_down_10s, "10")
                viewModel.countDown10sFinish().observe(this, Observer {
                    if (it == "finish") {
                        ARouter.getInstance().build(PassPath.PASS_MAIN).navigation()
                    } else {
                        binding.buttonCountDown.text = getString(R.string.count_down_10s, it)
                    }
                })
                binding.buttonCountDown.setOnClickListener {
                    ARouter.getInstance().build(PassPath.PASS_MAIN).navigation()
                }
            }
            1 -> {
                binding.buttonCountDown.visibility = View.GONE
            }
        }

        binding.callOrderDoneInfo.tv_done_002.text = orderDetail.orderNumber
        binding.callOrderDoneInfo.tv_done_01.text = orderDetail.driver.name
        binding.callOrderDoneInfo.tv_done_11.text = orderDetail.driverCarIdCard
        binding.callOrderDoneInfo.tv_done_21.text = orderDetail.driver.phone
        binding.callOrderDoneInfo.phone_done_call.setOnClickListener {
            AppCallAlertDialog(this).setContent(orderDetail.driver.phone)
                .setNavigation(getString(R.string.cancel), null)
                .setPositive(getString(R.string.call_phone),
                    View.OnClickListener {
                        val data = Uri.parse("tel:${orderDetail.driver.phone}")
                        val intent = Intent(Intent.ACTION_DIAL, data)
                        startActivity(intent)
                    }).show()
        }
    }

    private fun getCatTypeName(name: String?): String {
        return getString(R.string.passenger_car_type_with_colon) + if (name == null) getString(
            R.string.passenger_any_with_space
        ) else "$name "
    }

    private fun getTunnelName(name: String?): String {
        return getString(R.string.passenger_tunnel_with_colon) + if (name == null) getString(
            R.string.passenger_any_with_space
        ) else "$name "
    }

    private fun getStationName(name: Int?): String {
        return getString(R.string.passenger_station_with_colon)+ if (name == null || name == 0) getString(
            R.string.passenger_any_with_space
        ) else "$name "
    }

    private fun getRemark(name: String?): String {
        return  getString(R.string.passenger_remark_with_colon)+" " + if (name.isNullOrBlank() || name.isNullOrEmpty()) getString(
            R.string.none_with_space
        ) else "$name"
    }


}
